<?php

require_once(BASE_PATH."src/Object/Location/Town.php");
require_once(BASE_PATH."src/Object/Location/Province.php");
require_once(BASE_PATH."src/Object/Location/District.php");
require_once("GenericReader.php");

class DistrictReader extends GenericReader{
		
	public function __construct($object = NULL, $connection = NULL){
		parent::__construct($object, $connection);
	}
	
	public function execute(){
		$this->select = new RXSelect($this->connection);
		
		switch($this->operation){
			default: 
				return $this->executeGetOne();
		}
	}
		
	public function executeGetOne(){
		$query = "SELECT districts.*
										T.id as town_id, 
										T.name as town_name, 
										T.normalized_name as town_normalized_name,  
										P.id as province_id, 
										P.name as province_name, 
										P.normalized_name as province_normalized_name 
										FROM districts 
										INNER JOIN towns AS T ON districts.town = T.id  
										INNER JOIN provinces AS P ON T.province = P.id 
										WHERE districts.id = '".$this->object->getId()."'";
		$this->select->setQuery($query);
		return $this->select->execute();
	}
	
	public function executeTotal(){
		$this->select->addTable("districts");
		$this->select->addField("COUNT(*)", "total");
		return $this->select->execute();
	}
	
	public function next(){
		$row = $this->select->next();
		if($row){
			return new District(	$row["id"], 
												new Town(	$row["town_id"], 
													new Province($row["province_id"], 
														utf8_decode($row["province_name"]), 
														utf8_decode($row["province_normalized_name"])), 
													utf8_decode($row["town_name"]), 
													utf8_decode($row["town_normalized_name"])), 
												utf8_decode($row["name"]), 
												utf8_decode($row["normalized_name"]));	
		}else{
			return FALSE;
		}
	}
	
	public function getTotal(){
		$row = $this->select->next();
		return $row["total"];
	}
}